package util

import (
	"fmt"
	"log"
	"os"
	"sync"
	"time"

	models "openzbox.com/frame/echo/models/sl_gw01"
)

var (
	logger      *log.Logger
	logPrefix   = "log"
	currentTime = ""
)

func init() {
	//fmt.Println("log初始化")
	//获取当前时间
	//currentTime = time.Now().Format("20060102")
	//initName(currentTime)
}

func Error(v ...interface{}) {
	timenow := time.Now().Format("2006-01-02 15:04:05")
	//checkTime()
	//logger.SetPrefix("[Error] ")
	//logger.Println(v...)
	fmt.Println(v...)
	ErrorLogList = append(ErrorLogList, models.ErrorLog{
		Text:       v[0],
		CreateTime: timenow,
	})
	WriteMessage(timenow+"  "+v[0].(string), "2")
	if len(ErrorLogList) > 5000 {
		//超过5000条日志就清空
		ErrorLogList = ErrorLogList[:0]
	}
}

var (
	ModbusRTULogList []ModbusRTULog
	logMutex         sync.Mutex
)

func WriteRTULog(text string) {
	logMutex.Lock() // 加锁，确保只有一个goroutine能访问或修改日志列表
	timenow := time.Now().Format("2006-01-02 15:04:05")
	ModbusRTULogList = append(ModbusRTULogList, ModbusRTULog{
		Text:       text,
		CreateTime: timenow,
	})
	WriteMessage(timenow+"  "+text, "5")
	if len(ModbusRTULogList) > 5000 {
		//超过5000条日志就清空上一条
		ModbusRTULogList = ModbusRTULogList[1:]
	}
	logMutex.Unlock() // 解锁，允许其他goroutine访问日志列表
}

type ModbusRTULog struct {
	Text       interface{}
	CreateTime string
}

// 暂无用
func Info(v ...interface{}) {
	//timenow := time.Now().Format("2006-01-02 15:04:05")
	//checkTime(timenow)
	//logger.SetPrefix("[Info] ")
	//logger.Println(v...)
	fmt.Println(v...)
}
func MyPanic(v ...interface{}) {
	Error(v...)
	panic(v)
}

func initName(currentTimes string) {
	// 构造日志文件名
	logFileName := logPrefix + "/" + currentTimes + ".log"
	// 创建日志目录
	if err := os.MkdirAll(logPrefix, 0755); err != nil {
		fmt.Println("Failed to create log directory:", err)
	}
	file, err := os.OpenFile(logFileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println("Failed to open log file:", err)
	}
	//defer file.Close()
	// 初始化日志记录器
	logger = log.New(file, "", log.Ldate|log.Ltime|log.Lmicroseconds)
}

func checkTime() {
	timenow := time.Now().Format("20060102")
	if timenow != currentTime {
		//重新生成日志文件
		initName(timenow)
		currentTime = timenow
	}
}

// 去除重复的不采集展示日志
func IsCollectLog(logStr string) {
	isLog := false
	for _, log := range ErrorLogList {
		if log.Text == logStr {
			isLog = false
			break
		} else {
			isLog = true
		}
	}
	if isLog {
		Error(logStr)
	}
}
